<script lang="ts" setup>
import { useMap } from '@/hooks/useMap'
import { onMounted, reactive, ref, shallowRef } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const mapContainer = ref<HTMLDivElement>()
const isInit = ref<boolean>(false)
const marker = shallowRef<AMap.Marker>()
const watchParams = reactive({
  longtitude: Number(route.query.longtitude),
  latitude: Number(route.query.latitude),
})
const { map, initAmap } = useMap(mapContainer, [
  watchParams.longtitude ?? 0,
  watchParams.latitude ?? 0,
])

const handleCoverInit = () => {
  if (isInit.value && map.value) {
    map.value?.setCenter([watchParams.longtitude ?? 0, watchParams.latitude ?? 0])
    marker.value = new AMap.Marker({
      position: new AMap.LngLat(watchParams.longtitude ?? 0, watchParams.latitude ?? 0),
      map: map.value,
    })
    map.value.setFitView([marker.value])
  }
}
/** 地图初始化 */
const init = async () => {
  isInit.value = await initAmap()
  handleCoverInit()
}
onMounted(() => {
  init()
})
</script>

<template>
  <div class="xy-map-container">
    <div ref="mapContainer" id="map-container" />
  </div>
</template>
<style scoped lang="scss">
.xy-map-container {
  --at-apply: flex flex-col overflow-auto;
  width: 100%;
  height: 100%;
  > #map-container {
    flex: 1;
    position: relative;
  }
}
</style>
